using D.Medicalcare.Write.API;
using NLog.Web;
using System.Reflection;
using Yitter.IdGenerator;
using ServiceManagement.Consul;
using D.Medicalcare.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.OpenApi.Models;
using D.Medicalcare.Infrastructure.Implement;
using D.Medicalcare.Infrastructure.Interfaces;
using DocumentFormat.OpenXml.InkML;
using StackExchange.Redis;
using Essensoft.Paylink.Alipay;
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddSwaggerGen(x =>
{
    var path = AppDomain.CurrentDomain.BaseDirectory + "D.Medicalcare.Write.API.xml";
    x.IncludeXmlComments(path, true);

});
// 获取数据库连接字符串
var connectionString = builder.Configuration.GetConnectionString("DB");



// 使用 UseMySql 配置 MySQL 数据库连接
builder.Services.AddDbContext<MyDbContext>(options =>
    options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));
//仓储
builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
//中介者
builder.Services.AddMediatR(x => x.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));
//映射
builder.Services.AddAutoMapper(typeof(MappingProfile));
//日志
builder.Host.UseNLog();
//全局异常
builder.Services.AddControllers(x => x.Filters.Add<MyExceptionFilter>());
//雪花id
YitIdHelper.SetIdGenerator(new IdGeneratorOptions());
//注册consul
builder.Configuration.Register();


//授权认证（使用JWT）
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
{
    // 私钥
    var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
    o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
    {
        // 验证发布者
        ValidateIssuer = true,
        // 发布者信息
        ValidIssuer = "BeiJingBW",

        // 验证接收者
        ValidateAudience = true,
        // 接收者
        ValidAudience = "BeiJingBW",

        // 验证是否过期
        ValidateLifetime = true,

        // 验证私钥
        IssuerSigningKey = new SymmetricSecurityKey(secretByte)

    };
});

// 配置Swagger
builder.Services.AddSwaggerGen(o =>
{
    // 显示 授权信息
    o.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme()
    {
        Description = "添加JWT授权Token：Bearer Token值",
        Name = "Authorization",
        In = Microsoft.OpenApi.Models.ParameterLocation.Header,
        Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
        BearerFormat = "JWT",
        Scheme = "Bearer"
    });
    o.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[]
            {

            }
        }
    });
});

// 添加 Redis 服务
builder.Services.AddSingleton<IConnectionMultiplexer>(sp => ConnectionMultiplexer.Connect(builder.Configuration.GetConnectionString("Redis")));


//应用构建
//支付宝沙箱配置
builder.Services.AddAlipay();
builder.Services.Configure<AlipayOptions>(builder.Configuration.GetSection("Alipay"));

var app = builder.Build();
//跨域
app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
    app.UseSwagger();
    app.UseSwaggerUI();
//}
//静态文件
app.UseStaticFiles();

// 允许访问 wwwroot 文件夹
// 鉴权//认证授权中间件
app.UseAuthentication();

app.UseAuthorization();
// HTTPS 重定向
app.UseHttpsRedirection();
// 路由映射
app.MapControllers();

app.Run();